package com.lin.blog.controller;
import com.lin.blog.enmus.ResultCodeEnum;
import com.lin.blog.model.Result;
import com.lin.blog.model.UserInfo;
import com.lin.blog.service.UserService;
import com.lin.blog.utils.JwtUtils;
import com.lin.blog.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName,String password){
        if(!StringUtils.hasLength(userName)&&!StringUtils.hasLength(password)){
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(),"账号或密码不能为空");
        }
        //验证账号密码是否正确
        UserInfo userInfo=userService.selectUserInfoByName(userName);
        if(userInfo==null||userInfo.getId()==null){
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "用户不存在");
        }
        if(!SecurityUtils.verify(password,userInfo.getPassword())){
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
        }
//        if(!password.equals(userInfo.getPassword())){
//            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "密码错误");
//        }
        //账号密码正确的逻辑
        Map<String,Object> claims=new HashMap<>();
        claims.put("id",userInfo.getId());
        claims.put("name",userInfo.getUserName());
        String jwt=JwtUtils.genJwt(claims);
        return Result.success(jwt);
    }
    //利用Token获取id查询信息
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String userToken=request.getHeader("user_token_header");
        //从token中获取用户id
        Integer userId=JwtUtils.getUserIdFromToken(userToken);
        Assert.notNull(userId,"用户未登录");
        UserInfo userInfo=userService.selectUserInfoById(userId);
        return userInfo;
    }
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        Assert.notNull(blogId,"博客id不能为null");
        return userService.selectAuthorInfoByBlogId(blogId);
    }
}
